<?php 
/****
author:N++
email:
license:
****/

namespace Home\Model;
use Think\Model;

class UserModel extends Model{
	//注册时自动验证规则
	protected $_validate= array(
        // //array(验证字段,验证规则,错误提示,[验证条件,附加规则,验证时间])
        array('username','','帐号名称已经存在！',1,'unique',3),
        array('username','/^\w{5,16}$/','用户名需为5-16位数字,字母或者下划线',1,'regex',3),
        array('email','','email已注册!',1,'unique',3),
        array('email','email','请输入正确email',1,'regx',3),
        array('password','/^\w{6,16}$/','密码需为6-12位数字,字母或者下划线',1,'regex',3),
        array('confirm_password','password','两次输入密码不一致', 1 ,'confirm',3),
        // array('input_verify','require','请输入验证码',1,),
        // array('input_verify','verify','验证码错误.', 1 ,'confirm',3),
        );

	//授权,设置cookie
	public function auth(){
		cookie('user_id',$this->user_id);
		cookie('username',$this->username);
	}

	//收回权限 清除cookie
	public function revoke(){
		cookie('user_id',null);
		cookie('username',null);
	}

	//登陆验证
	public function logverify($checkdata){
		return where($checkdata)->find();
	}
	//登陆密码校对
	public function checkPass($password){
		$realpass = $this->password;//将收到find()时产生的密码存入$realpassword
		$this->password = $password;//把密码修改为post来的明文密码
		$this->encPass();

		return ($this->password === $realpass);
	}

	//注册时MD5加密
	public function regmd5(){
		$this->encPass();
		return $this->add();
	}

	//产生加密密码
	public function encPass(){
		$this->salt();
		$this->password = md5($this->salt.$this->password);
	}

	// 产生salt
	public function salt(){
		if(!isset($this->salt)){
			$this->salt = $this->randStr();
		}
		return $this->salt;
	}

	//获取随机字符串
	public function randStr($length = 8){
		$str = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ123456789";
		$str = str_shuffle($str);
		return substr($str,0,$length);
	}
}

?>